package top.xshiwu.demo.service;



import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.listener.KeyspaceEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import top.xshiwu.demo.configure.FastJson2JsonRedisSerializer;
import top.xshiwu.demo.mo.NetworkMO;

import javax.mail.MessagingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 *
 * @author hy
 * @createTime 2021-05-01 08:53:19
 * @description 期望是可以监听某个key的变化，而不是失效
 *
 */
@Slf4j
public class RDMessageEvent implements MessageListener, InitializingBean, DisposableBean {




    private static final Topic TOPIC_ALL_KEYEVENTS = new PatternTopic("notify:network:project:*");
    private final RedisMessageListenerContainer listenerContainer;
    private String keyspaceNotificationsConfigParameter = "EA";

    public  RDMessageEvent(RedisMessageListenerContainer listenerContainer) {
        Assert.notNull(listenerContainer, "RedisMessageListenerContainer to run in must not be null!");
        this.listenerContainer = listenerContainer;
    }

    public void onMessage(Message message, @Nullable byte[] pattern) {
        if (!ObjectUtils.isEmpty(message.getChannel()) && !ObjectUtils.isEmpty(message.getBody())) {
            this.doHandleMessage(message);
        }
    }

    /**
     * 时间格式
     */
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @SneakyThrows
    protected void doHandleMessage(Message message){

        String jsonStr = new String(message.getBody());
        log.info("jsonStr:" + jsonStr);
        String simpleJson = replaceAll(jsonStr);
        log.info("simpleJson:" + simpleJson);
        NetworkMO networkMO = JSON.parseObject(simpleJson,NetworkMO.class);



        Boolean isOnline = networkMO.getOnline();
        String title = isOnline ? "设备上线通知":"设备离线通知";
        Long projectId = networkMO.getProjectId();
        String projectName = networkMO.getProjectName();
        String devId =  networkMO.getDevId();
        String remark = networkMO.getRemark();
        String time = df.format(networkMO.getTime());
        StringBuilder builder = new StringBuilder();
        builder.append(projectName).append("\n")
                .append(devId).append("号设备").append("[")
                .append(remark).append("]")
                .append("于").append(time);
        if(isOnline) {
            builder.append("上线");
        } else {
            builder.append("离线");
        }

        for(INotifyEmail notify: notifyEmails) {
         notify.notify(projectId,title,builder.toString());
        }
    }

    public static String replaceAll(String str){
        String replaceAll3 = null;
        if(!StringUtils.isEmpty(str)){
            String replaceAll = str.replaceAll("\\\\", "");
            System.out.println(replaceAll);
            String replaceAll2 = replaceAll.replaceAll("\"[{]", "{");
            replaceAll3 = replaceAll2.replaceAll("[}]\"", "}");
        }

        return replaceAll3;
    }

    List<INotifyEmail> notifyEmails = new ArrayList<>();
    public void addNotifyEmailListen(INotifyEmail iNotifyEmail) {
        notifyEmails.add(iNotifyEmail);
    }
    public void removeNotifyEmailListen(INotifyEmail iNotifyEmail) {
        notifyEmails.remove(iNotifyEmail);
    }


   public  interface INotifyEmail {
        void notify(Long projectId,String title,String content) throws MessagingException;
    }




    public void init() {
        if (StringUtils.hasText(this.keyspaceNotificationsConfigParameter)) {
            RedisConnection connection = this.listenerContainer.getConnectionFactory().getConnection();

            try {
                Properties config = connection.getConfig("notify-keyspace-events");
                if (!StringUtils.hasText(config.getProperty("notify-keyspace-events"))) {
                    connection.setConfig("notify-keyspace-events", this.keyspaceNotificationsConfigParameter);
                }
            } finally {
                connection.close();
            }
        }

        this.doRegister(this.listenerContainer);
    }

    protected void doRegister(RedisMessageListenerContainer container) {
        this.listenerContainer.addMessageListener(this, TOPIC_ALL_KEYEVENTS);
    }

    public void destroy() throws Exception {
        this.listenerContainer.removeMessageListener(this);
    }

    public void setKeyspaceNotificationsConfigParameter(String keyspaceNotificationsConfigParameter) {
        this.keyspaceNotificationsConfigParameter = keyspaceNotificationsConfigParameter;
    }

    public void afterPropertiesSet() throws Exception {
        this.init();
    }
}